<template>
  <div class="app-container">
    <el-card class="search-card">
      <el-form :model="queryParams" ref="queryForm" :inline="true" class="search-form">
        <el-form-item label="所属测试" prop="testId">
          <el-select v-model="queryParams.testId" placeholder="请选择所属测试" clearable style="width: 200px">
            <el-option
              v-for="test in testOptions"
              :key="test.id"
              :label="test.title"
              :value="test.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="题目内容" prop="questionText">
          <el-input
            v-model="queryParams.questionText"
            placeholder="请输入题目内容"
            clearable
            style="width: 200px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="题目类型" prop="questionType">
          <el-select v-model="queryParams.questionType" placeholder="请选择题目类型" clearable style="width: 150px">
            <el-option label="单选题" :value="1" />
            <el-option label="多选题" :value="2" />
            <el-option label="量表题" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="维度" prop="dimension">
          <el-select v-model="queryParams.dimension" placeholder="请选择维度" clearable style="width: 150px">
            <el-option
              v-for="dim in dimensionOptions"
              :key="dim.dimensionKey"
              :label="dim.dimensionName"
              :value="dim.dimensionKey"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleQuery">搜索</el-button>
          <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="action-card">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            :icon="Plus"
            @click="handleAdd"
          >新增题目</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            :icon="Upload"
            @click="handleImport"
          >批量导入</el-button>
        </el-col>
      </el-row>

      <el-table
        v-loading="loading"
        :data="questionList"
        border
        stripe
        style="width: 100%"
        :header-cell-style="{background:'#f5f7fa', color:'#606266'}"
      >
        <el-table-column label="所属测试" align="center" prop="testName" min-width="150" show-overflow-tooltip>
          <template #default="scope">
            <span>{{ getTestName(scope.row.testId) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="题目内容" align="left" prop="questionText" min-width="250" show-overflow-tooltip>
          <template #default="scope">
            <div class="question-text">{{ scope.row.questionText }}</div>
          </template>
        </el-table-column>
        <el-table-column label="题目类型" align="center" prop="questionType" width="100">
          <template #default="scope">
            <el-tag :type="getQuestionTypeTag(scope.row.questionType)" effect="plain">
              {{ getQuestionTypeLabel(scope.row.questionType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="分值" align="center" prop="score" width="80">
          <template #default="scope">
            <el-tag type="info" effect="plain">{{ scope.row.score || 0 }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="维度" align="center" prop="dimension" width="120">
          <template #default="scope">
            <el-tag type="warning" effect="plain">{{ getDimensionText(scope.row.dimension) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="排序" align="center" prop="sortNum" width="80">
          <template #default="scope">
            <span class="sort-number">{{ scope.row.sortNum }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="180">
          <template #default="scope">
            <el-button
              type="text"
              @click="handleEdit(scope.row)"
            >编辑</el-button>
            <el-button
              type="text"
              style="color: #ff4949"
              @click="handleDelete(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
        class="pagination-container"
      />
    </el-card>

    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="questionForm" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="所属测试" prop="testId">
          <el-select 
            v-model="form.testId" 
            placeholder="请选择所属测试"
            @change="handleTestChange"
          >
            <el-option
              v-for="test in testOptions"
              :key="test.id"
              :label="test.title"
              :value="test.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="题目类型" prop="questionType">
          <el-select v-model="form.questionType" placeholder="请选择题目类型">
            <el-option label="单选题" :value="1" />
            <el-option label="多选题" :value="2" />
            <el-option label="量表题" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="维度" prop="dimension">
          <el-select v-model="form.dimension" placeholder="请选择维度">
            <el-option
              v-for="dim in dimensionOptions"
              :key="dim.dimensionKey"
              :label="dim.dimensionName"
              :value="dim.dimensionKey"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="题目内容" prop="questionText">
          <el-input v-model="form.questionText" type="textarea" :rows="3" placeholder="请输入题目内容" />
        </el-form-item>
        <el-form-item label="选项" prop="options" v-if="form.questionType === 3">
          <div class="scale-options">
            <div v-for="(option, index) in optionContents" :key="index" class="scale-option-item">
              <span class="option-label">{{ optionLabels[index] }}:</span>
              <el-input v-model="optionContents[index]" style="width: calc(100% - 40px)"/>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="选项分值" prop="optionScores" v-if="form.questionType === 3">
          <div class="scale-options">
            <div class="score-row">
              <div v-for="(option, index) in optionContents" :key="index" class="score-item">
                <span class="score-label">选{{ optionLabels[index] }}({{ option }})得分:</span>
                <el-input-number v-model="optionScores[index]" :min="1" :max="4" controls-position="right" />
              </div>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="分值" prop="score">
          <el-input-number v-model="form.score" :min="1" :max="100" />
        </el-form-item>
        <el-form-item label="排序" prop="sortNum">
          <el-input-number v-model="form.sortNum" :min="1" :max="999" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog title="题目预览" v-model="previewOpen" width="600px" append-to-body>
      <div class="preview-content">
        <div class="preview-item">
          <div class="preview-label">所属测试：</div>
          <div class="preview-value">{{ previewData.testName }}</div>
        </div>
        <div class="preview-item">
          <div class="preview-label">题目类型：</div>
          <div class="preview-value">{{ getQuestionTypeLabel(previewData.questionType) }}</div>
        </div>
        <div class="preview-item">
          <div class="preview-label">维度：</div>
          <div class="preview-value">{{ getDimensionText(previewData.dimension) }}</div>
        </div>
        <div class="preview-item">
          <div class="preview-label">题目内容：</div>
          <div class="preview-value">{{ previewData.questionText }}</div>
        </div>
        <div class="preview-item" v-if="previewData.options && previewData.options.length > 0">
          <div class="preview-label">选项：</div>
          <div class="preview-value">
            <div v-for="(option, index) in previewData.options" :key="index">
              {{ optionLabels[index] }}. {{ option }}
            </div>
          </div>
        </div>
        <div class="preview-item">
          <div class="preview-label">分值：</div>
          <div class="preview-value">{{ previewData.score }}</div>
        </div>
      </div>
    </el-dialog>

    <el-dialog title="批量导入题目" v-model="importOpen" width="500px" append-to-body>
      <el-form ref="importForm" :model="importForm" :rules="importRules" label-width="100px">
        <el-form-item label="所属测试" prop="testId">
          <el-select v-model="importForm.testId" placeholder="请选择所属测试">
            <el-option
              v-for="test in testOptions"
              :key="test.id"
              :label="test.title"
              :value="test.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="Excel文件" prop="file">
          <el-upload
            class="upload-demo"
            :action="uploadUrl"
            :headers="headers"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :before-upload="beforeUpload"
            accept=".xlsx, .xls"
          >
            <el-button type="primary">选择文件</el-button>
            <template #tip>
              <div class="el-upload__tip">
                只能上传xlsx/xls文件，且文件大小不超过10MB
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitImport">确 定</el-button>
          <el-button @click="cancelImport">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { listQuestions, getQuestionDetail, addQuestion, updateQuestion, deleteQuestion } from '@/api/psychological-test'
import { listTests, getTestDetail } from '@/api/psychological-test'
import { getToken } from '@/utils/auth'
import { Search, Refresh, Plus, Upload, Edit, View, Delete } from '@element-plus/icons-vue'

export default {
  name: 'QuestionBank',
  components: {
    Search,
    Refresh,
    Plus,
    Upload,
    Edit,
    View,
    Delete
  },
  data() {
    return {
      loading: false,
      total: 0,
      questionList: [],
      title: '',
      open: false,
      previewOpen: false,
      importOpen: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        testId: undefined,
        questionText: undefined,
        questionType: undefined,
        dimension: undefined
      },
      form: {
        id: undefined,
        testId: undefined,
        questionType: 3,
        questionText: '',
        options: ['很少', '有时', '经常', '总是'],
        score: 4,
        dimension: undefined,
        sortNum: 1
      },
      rules: {
        testId: [
          { required: true, message: '请选择所属测试', trigger: 'change' }
        ],
        questionType: [
          { required: true, message: '请选择题目类型', trigger: 'change' }
        ],
        dimension: [
          { required: true, message: '请选择维度', trigger: 'change' }
        ],
        questionText: [
          { required: true, message: '请输入题目内容', trigger: 'blur' }
        ],
        options: [
          { 
            type: 'array', 
            required: true, 
            message: '请至少添加两个选项', 
            trigger: 'change',
            validator: (rule, value, callback) => {
              if (this.form.questionType !== 3 && (!value || value.length < 2)) {
                callback(new Error('至少需要添加两个选项'));
              } else {
                callback();
              }
            }
          }
        ],
        score: [
          { required: true, message: '请输入分值', trigger: 'blur' }
        ],
        sortNum: [
          { required: true, message: '请输入排序号', trigger: 'blur' }
        ]
      },
      importForm: {
        testId: undefined,
        file: undefined
      },
      importRules: {
        testId: [
          { required: true, message: '请选择所属测试', trigger: 'change' }
        ],
        file: [
          { required: true, message: '请选择Excel文件', trigger: 'change' }
        ]
      },
      questionTypeOptions: [
        { label: '单选题', value: 1 },
        { label: '多选题', value: 2 },
        { label: '量表题', value: 3 }
      ],
      optionLabels: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K'],
      optionContents: [],
      optionScores: [1, 2, 3, 4],
      testOptions: [],
      dimensionOptions: [],
      previewData: {},
      uploadUrl: process.env.VUE_APP_BASE_API + '/api/test-questions/import',
      headers: {
        Authorization: 'Bearer ' + getToken()
      },
      dimensionMap: {
        'EMOTIONAL': '情感症状',
        'SOMATIC': '躯体症状',
        'COGNITIVE': '认知症状',
        'PSYCHOMOTOR': '精神运动症状'
      }
    }
  },
  created() {
    this.getList()
    this.getTestOptions()
    this.getAllDimensions()
  },
  methods: {
    getList() {
      this.loading = true
      listQuestions(this.queryParams).then(response => {
        const uniqueQuestions = Array.from(new Map(response.data.records.map(item => [item.id, item])).values())
        this.questionList = uniqueQuestions
        this.total = response.data.total
        this.loading = false
      })
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        testId: undefined,
        questionText: undefined,
        questionType: undefined,
        dimension: undefined
      }
      this.handleQuery()
    },
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加题目'
      if (this.form.questionType === 3) {
        this.optionContents = ['很少', '有时', '经常', '总是']
        this.form.options = this.optionContents
      }
    },
    handleEdit(row) {
      this.reset()
      const id = row.id
      getQuestionDetail(id).then(response => {
        this.form = response.data
        if (this.form.questionType === 3) {
          this.optionContents = Array.isArray(this.form.options) ? this.form.options : []
          
          if (this.form.optionScores) {
            this.optionScores = Object.keys(this.form.optionScores)
              .sort((a, b) => Number(a) - Number(b))
              .map(key => this.form.optionScores[key])
          } else {
            this.optionScores = Array(this.optionContents.length).fill(1)
          }
        } else {
          this.optionContents = Array.isArray(this.form.options) ? 
            [...this.form.options] : 
            (typeof this.form.options === 'string' ? 
              JSON.parse(this.form.options) : 
              [])
        }
        this.open = true
        this.title = '修改题目'
      })
    },
    handlePreview(row) {
      this.previewData = { ...row }
      this.previewOpen = true
    },
    handleImport() {
      this.importForm = {
        testId: undefined,
        file: undefined
      }
      this.importOpen = true
    },
    submitForm() {
      this.$refs['questionForm'].validate(valid => {
        if (valid) {
          const data = {
            testId: this.form.testId,
            questionType: this.form.questionType,
            questionText: this.form.questionText,
            dimension: this.form.dimension,
            score: this.form.score,
            sortNum: this.form.sortNum,
            analysis: this.form.analysis,
            options: this.optionContents.filter(item => item),
            optionScores: this.form.questionType === 3 ? 
              this.optionContents.reduce((acc, _, index) => {
                acc[index + 1] = this.optionScores[index]
                return acc
              }, {}) : undefined
          }
          console.log('Submitting data:', data)

          if (this.form.id) {
            updateQuestion(this.form.id, data).then(response => {
              this.$message.success('修改成功')
              this.open = false
              this.getList()
            }).catch(error => {
              console.error('更新失败:', error)
              this.$message.error(error.message || '操作失败，请稍后重试')
            })
          } else {
            addQuestion(data).then(response => {
              this.$message.success('新增成功')
              this.open = false
              this.getList()
            }).catch(error => {
              console.error('添加失败:', error)
              this.$message.error(error.message || '操作失败，请稍后重试')
            })
          }
        }
      })
    },
    handleDelete(row) {
      const id = row.id
      this.$confirm('是否确认删除该题目？', '提示', {
        type: 'warning'
      }).then(() => {
        deleteQuestion(id).then(() => {
          this.$message.success('删除成功')
          this.getList()
        }).catch(error => {
          this.$message.error(error.message || '删除失败，请稍后重试')
        })
      }).catch(() => {})
    },
    cancel() {
      this.open = false
      this.reset()
    },
    cancelImport() {
      this.importOpen = false
      this.importForm = {
        testId: undefined,
        file: undefined
      }
    },
    reset() {
      this.form = {
        id: undefined,
        testId: undefined,
        questionType: 3,
        questionText: '',
        options: ['很少', '有时', '经常', '总是'],
        score: 4,
        dimension: undefined,
        sortNum: 1
      }
      this.optionContents = []
      this.optionScores = [1, 2, 3, 4]
      if (this.$refs['questionForm']) {
        this.$refs['questionForm'].resetFields()
      }
    },
    addOption() {
      if (this.form.options.length < this.optionLabels.length) {
        const nextIndex = this.form.options.length
        this.form.options.push(this.optionLabels[nextIndex] + '.')
        this.optionContents.push('')
      } else {
        this.$modal.msgWarning('最多只能添加' + this.optionLabels.length + '个选项')
      }
    },
    removeOption(index) {
      this.form.options.splice(index, 1)
      this.optionContents.splice(index, 1)
      this.form.options = this.form.options.map((opt, i) => 
        this.optionLabels[i] + '.' + this.optionContents[i]
      )
    },
    updateOption(index) {
      this.form.options[index] = this.optionLabels[index] + '.' + this.optionContents[index]
    },
    handleMultiAnswerChange(values) {
      this.form.correctAnswer = values.sort().join(',')
    },
    getTestOptions() {
      listTests({ pageSize: 999 }).then(response => {
        this.testOptions = response.data.records
      })
    },
    handleTestChange(testId) {
      if (testId) {
        getTestDetail(testId).then(response => {
          this.dimensionOptions = response.data.dimensions || []
        })
      } else {
        this.dimensionOptions = []
      }
    },
    getAllDimensions() {
      listTests({ pageSize: 999 }).then(response => {
        const tests = response.data.records || []
        const promises = tests.map(test => getTestDetail(test.id))
        Promise.all(promises).then(responses => {
          const allDimensions = []
          responses.forEach(res => {
            if (res.data && res.data.dimensions) {
              allDimensions.push(...res.data.dimensions)
            }
          })
          this.dimensionOptions = Array.from(new Map(allDimensions.map(item => [item.dimensionKey, item])).values())
        })
      })
    },
    getDimensionText(dimension) {
      return this.dimensionMap[dimension] || dimension || '未设置'
    },
    getQuestionTypeLabel(type) {
      switch (type) {
        case 1: return '单选题'
        case 2: return '多选题'
        case 3: return '量表题'
        default: return '未知类型'
      }
    },
    getQuestionTypeTag(type) {
      switch (type) {
        case 1: return 'success'
        case 2: return 'warning'
        case 3: return 'info'
        default: return 'danger'
      }
    },
    beforeUpload(file) {
      const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || 
                      file.type === 'application/vnd.ms-excel'
      const isLt10M = file.size / 1024 / 1024 < 10

      if (!isExcel) {
        this.$message.error('只能上传Excel文件!')
        return false
      }
      if (!isLt10M) {
        this.$message.error('文件大小不能超过 10MB!')
        return false
      }
      return true
    },
    handleUploadSuccess(response, file) {
      if (response.code === 200) {
        this.$message.success('文件上传成功')
        this.importForm.file = file.raw
      } else {
        this.$message.error(response.msg || '文件上传失败')
      }
    },
    handleUploadError() {
      this.$message.error('文件上传失败')
    },
    submitImport() {
      this.$refs['importForm'].validate(valid => {
        if (valid) {
          if (!this.importForm.file) {
            this.$message.error('请选择要上传的文件')
            return
          }
          // TODO: 实现文件上传和导入逻辑
          this.$message.success('导入成功')
          this.importOpen = false
          this.getList()
        }
      })
    },
    getTestName(testId) {
      const test = this.testOptions.find(t => t.id === testId)
      return test ? test.title : ''
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
  background-color: #f0f2f5;
}

.search-card {
  margin-bottom: 20px;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
}

.search-form {
  padding: 18px 0 0;
}

.action-card {
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
}

.mb8 {
  margin-bottom: 16px;
}

.question-text {
  padding: 8px 0;
  line-height: 1.5;
  text-align: left;
}

.sort-number {
  display: inline-block;
  min-width: 26px;
  height: 26px;
  line-height: 26px;
  text-align: center;
  background-color: #f5f7fa;
  border-radius: 13px;
  color: #606266;
}

.pagination-container {
  padding: 15px 0;
  text-align: center;
}

.option-item {
  margin-bottom: 12px;
  background-color: #f8f9fb;
  border-radius: 4px;
  padding: 8px;
}

.option-input-group {
  display: flex;
  align-items: center;
}

.option-label {
  width: 30px;
  text-align: right;
  margin-right: 12px;
  font-weight: bold;
  color: #606266;
}

.preview-content {
  padding: 24px;
  background-color: #f8f9fb;
  border-radius: 4px;
}

.preview-item {
  margin-bottom: 16px;
  border-bottom: 1px dashed #e6e6e6;
  padding-bottom: 16px;
}

.preview-item:last-child {
  margin-bottom: 0;
  border-bottom: none;
  padding-bottom: 0;
}

.preview-label {
  font-weight: bold;
  margin-bottom: 8px;
  color: #606266;
}

.preview-value {
  color: #333;
  line-height: 1.6;
}

.upload-demo {
  margin-bottom: 12px;
}

.el-upload__tip {
  line-height: 1.4;
  padding-top: 8px;
  color: #909399;
}

:deep(.el-table) {
  margin: 16px 0;
}

:deep(.el-table th) {
  background-color: #f5f7fa !important;
  color: #606266;
  font-weight: bold;
}

:deep(.el-table td) {
  padding: 12px 0;
}

:deep(.el-tag) {
  margin: 0 4px;
}

:deep(.el-button) {
  padding: 8px 16px;
}

:deep(.el-form-item) {
  margin-bottom: 18px;
  margin-right: 18px;
}

:deep(.el-card__body) {
  padding: 20px;
}

.operation-buttons {
  display: inline-flex;
  align-items: center;
}

:deep(.el-button-group) {
  display: inline-flex;
  align-items: center;
}

:deep(.el-button-group .el-button--link) {
  height: 28px;
  padding: 0 8px;
  margin: 0;
}

:deep(.el-divider--vertical) {
  height: 16px;
  margin: 0 4px;
}

:deep(.el-button--link .el-icon) {
  margin-right: 4px;
}

:deep(.el-button--link) {
  padding: 2px 4px;
}

:deep(.el-button--link + .el-button--link) {
  margin-left: 8px;
}

:deep(.el-button--text) {
  padding: 0 8px;
}

.scale-options {
  width: 100%;
}

.scale-option-item {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
  padding-left: 0;
}

.scale-option-item:last-child {
  margin-bottom: 0;
}

.scale-option-item .option-label {
  width: 30px;
  text-align: left;
  margin-right: 10px;
  color: #606266;
}

.scale-option-item .el-input {
  width: calc(100% - 40px);
}

.score-row {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.score-item {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.score-label {
  min-width: 120px;
  margin-right: 12px;
  color: #606266;
}

:deep(.el-input-number) {
  width: 120px;
}
</style> 